package com.oneraku.service.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Author: hui.ren@huberbuy.com
 * @Date: 2020/1/15 17:44
 */
@Configuration
@EnableConfigurationProperties({HikariConfigProperties.class})
public class DataSourceConfig {
    @Bean
    public DataSource dataSource(@Autowired  HikariConfigProperties properties) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(properties.getJdbcUrl());
        config.setUsername(properties.getUsername());
        config.setPassword(properties.getPassword());
        config.setMinimumIdle(properties.getMinimumIdle());
        config.setMaximumPoolSize(properties.getMaximumPoolSize());
        config.setConnectionInitSql(properties.getConnectionInitSql());
        config.setConnectionTestQuery(properties.getConnectionTestQuery());
        config.setConnectionTimeout(properties.getConnectionTimeout());
        config.setValidationTimeout(properties.getValidationTimeout());
        config.setLeakDetectionThreshold(properties.getLeakDetectionThreshold());
        config.setMaxLifetime(properties.getMaxLifetime());
        config.setCatalog(properties.getCatalog());
        config.setInitializationFailTimeout(properties.getInitializationFailTimeout());
        config.setDriverClassName(properties.getDriverClassName());
        config.setJdbcUrl(properties.getJdbcUrl());
        config.setPoolName(properties.getPoolName());
        config.setAllowPoolSuspension(false);
        config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("useLocalTransactionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        HikariDataSource ds = new HikariDataSource(config);
        return ds;
    }
}
